<template>
  <div class="app-container">
    <div class="top">
      <el-input
        v-model="kwInput"
        placeholder="输入 名称 或 属性 进行筛选"
        class="input-with-select"
        clearable
        :disabled="!listLoading"
        @keyup.native.enter="handleSearch"
      >
        <el-button slot="append" icon="el-icon-search" @click="handleSearch">搜索</el-button>
      </el-input>
      <el-button
        type="primary"
        class="el-icon-plus add-btn"
        :disabled="!listLoading"
        @click="handleAction('create', '添加项目')"
      >添加公司
      </el-button>
    </div>

    <div class="filter-container">
      <el-select
        v-model="vipGradeFilter"
        placeholder="VIP等级"
        clearable
        style="width: 120px; margin-right: 10px;"
        @change="handleSearch"
      >
        <el-option label="全部" value="" />
        <el-option label="0级" value="0" />
        <el-option label="1级" value="1" />
        <el-option label="2级" value="2" />
        <el-option label="3级" value="3" />
        <el-option label="4级" value="4" />
        <el-option label="5级" value="5" />
      </el-select>

      <el-select
        v-model="isEnableFilter"
        placeholder="是否启用"
        clearable
        style="width: 120px; margin-right: 10px;"
        @change="handleSearch"
      >
        <el-option label="全部" value="" />
        <el-option label="启用" value="true" />
        <el-option label="禁用" value="false" />
      </el-select>
    </div>

    <div style="float: right; margin-right: 8px;margin-bottom: 5px">
      <!--      <el-button size="mini" type="warning" @click="handleEditProjectAttr(projectSelected)">修改选中项 项目模版属性-->
      <!--      </el-button>-->
      <el-button size="mini" type="success" @click="handleSendDingdingMsg(projectSelected)">发送钉钉消息</el-button>
    </div>
    <el-table
      v-loading.body="!listLoading"
      :data="data"
      border
      fit
      highlight-current-row
      style="width: 100%"
      @selection-change="handleSelectionChange"
      @sort-change="handleSort"
    >
      <el-table-column
        type="selection"
        show-overflow-tooltip
        width="55"
      />

      <el-table-column align="center" width="100" prop="id" label="id" sortable="custom" />

      <el-table-column align="center" label="名称">
        <template slot-scope="scope">
          <template v-if="scope.row.edit">
            <el-input v-model="scope.row.name" class="name-input" size="mini" />
            <el-input v-model="scope.row.dingding_alert_link" class="name-input" size="mini" />
            <el-button
              type="success"
              size="mini"
              icon="el-icon-circle-check-outline"
              @click="handleUpdateName(scope.row)"
            >确认
            </el-button>
            <el-button type="warning" size="mini" icon="el-icon-edit" @click="handleCancelName(scope.row)">取消
            </el-button>
          </template>
          <template v-else>
            <span style="display: block;">{{ scope.row.name }}</span>
            <span>{{ getDingdingLinkDisplay(scope.row.dingding_alert_link) }}</span>
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="scope.row.edit = true"
            />

          </template>
        </template>
      </el-table-column>

      <el-table-column align="center" label="是否启用" width="100">
        <template slot-scope="scope">
          <el-tag :type="scope.row.isEnable ? 'success' : 'info'">
            {{ scope.row.isEnable ? '是' : '否' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="VIP等级" width="150">
        <template slot-scope="scope">
          <el-tag :type="scope.row.vip_grade > 0 ? 'success': 'info'">
            {{ scope.row.vip_grade }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="NPC企业" width="150">
        <template slot-scope="scope">
          <el-tag :type="scope.row.is_npc ? 'primary' : 'info'">
            {{ scope.row.is_npc ? '是' : '否' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="标题必须审核" width="150">
        <template slot-scope="scope">
          <el-tag :type="scope.row.is_seo_title_need_check ? 'primary' : 'info'">
            {{ scope.row.is_seo_title_need_check ? '是' : '否' }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" label="到期时间" prop="end_date" width="180" sortable="custom">
        <template slot-scope="scope">
          <span :class="getExpiryStatusClass(scope.row.end_date)" :title="getExpiryStatusText(scope.row.end_date)">
            {{ scope.row.end_date || '未设置' }}
          </span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="操作" width="300">
        <template slot-scope="scope">
          <el-button size="mini" type="danger" plain @click="handleAction('staffs', scope.row)">员工</el-button>
          <!--          <el-button type="warning" size="mini" icon="el-icon-setting"-->
          <!--                     @click="handleEditProjectAttr(scope.row)">公司属性-->
          <!--          </el-button>-->
          <el-button size="mini" type="primary" plain @click="handleAction('edit', scope.row)">修改</el-button>
          <el-button size="mini" type="danger" plain @click="handleAction('delete', scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-if="data.length"
      background
      class="mt-pagination"
      :current-page="page"
      :page-sizes="[10,20,50,100]"
      :page-size="pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handlePageChange"
    />

    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      width="30%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form v-if="action !== 'delete'" ref="dataForm" :model="temp" label-position="left" label-width="120px">
        <el-form-item label="名称">
          <el-input v-model="temp.name" />
        </el-form-item>
        <el-form-item label="钉钉提醒URL">
          <el-input v-model="temp.dingding_alert_link" />
        </el-form-item>
        <el-form-item label="服务截止时间">
          <el-date-picker
            v-model="temp.end_date"
            type="datetime"
            placeholder="选择截止时间"
            value-format="yyyy-MM-dd HH:mm:ss"
            :picker-options="datePickerOptions"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="是否启用">
          <el-switch
            v-model="temp.isEnable"
            active-color="#13ce66"
            inactive-color="#ff4949"
          />
        </el-form-item>
        <el-form-item label="VIP等级">
          <el-input v-model="temp.vip_grade" type="number" max="5" />
        </el-form-item>
        <el-form-item label="NPC企业">
          <el-switch
            v-model="temp.is_npc"
            active-color="#13ce66"
            inactive-color="#ff4949"
          />
        </el-form-item>
        <el-form-item label="标题强制审核">
          <el-switch
            v-model="temp.is_seo_title_need_check"
            active-color="#13ce66"
            inactive-color="#ff4949"
          />
        </el-form-item>
        <el-form-item label="自动翻译">
          <el-switch
            v-model="temp.auto_post_translate"
            active-color="#13ce66"
            inactive-color="#ff4949"
          />
        </el-form-item>
        <el-form-item label="启用增量翻译">
          <el-switch
            v-model="temp.enable_incremental_translation"
            active-color="#13ce66"
            inactive-color="#ff4949"
          />
        </el-form-item>
        <el-form-item label="增量翻译阈值">
          <el-input v-model="temp.incremental_translation_threshold" type="number" max="100" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button :type="action !== 'delete'?'primary':'danger'" @click="confirm">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="发送钉钉消息"
      :visible.sync="dingdingDialogVisible"
      width="30%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form ref="dingdingForm" :model="dingdingForm" label-position="left" label-width="80px">
        <el-form-item label="消息内容">
          <el-input
            v-model="dingdingForm.content"
            type="textarea"
            :rows="4"
            placeholder="请输入消息内容"
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dingdingDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmSendDingding">发 送</el-button>
      </span>
    </el-dialog>
    <!--    <project-attr-->
    <!--      :project_id="currentProjectId"-->
    <!--      :templateDialogVisible="projectAttrDialogVisible"-->
    <!--      @reload="getList"-->
    <!--      @cancelProjectAttrDialog="cancelProjectAttrDialog($event)"></project-attr>-->

  </div>
</template>

<script>
import { Get, Post, Put, Delete } from '@/api/erp/elicink/project.js'
import { Post as SendDingdingMsg } from '@/api/crm/crmdingdingmessage'
import projectAttr from './elements/projectAttr'
import qs from 'qs'

const orderMapper = {
  'ascending': 0,
  'descending': 1,
  'null': ''
}

export default {
  name: 'ProjectManage',
  components: { projectAttr },
  data() {
    return {
      data: [],
      dingdingDialogVisible: false,
      dingdingForm: {
        content: '',
        project_id: null
      },
      listLoading: true,
      kwInput: '',
      vipGradeFilter: '', // VIP等级过滤
      isEnableFilter: '', // 是否启用过滤
      order_by: '',
      order_desc: '',
      // pagination
      pagesize: 100,
      page: 1,
      total: 0,

      action: null,
      dialogVisible: false,
      title: '',
      temp: {
        name: '',
        dingding_alert_link: '',
        vip_grade: 0,
        isEnable: true,
        is_seo_title_need_check: false,
        is_npc: false,
        end_date: '',
        auto_post_translate: false,
        enable_incremental_translation: true,
        incremental_translation_threshold: 70
      },

      // 项目属性表单
      currentProjectId: null,
      prjectAttrForm: {},
      projectAttrDialogVisible: false,

      projectSelected: [],
      datePickerOptions: {
        shortcuts: [
          {
            text: '1年',
            onClick(picker) {
              const date = new Date()
              date.setFullYear(date.getFullYear() + 1)
              date.setHours(23, 59, 59, 999)
              picker.$emit('pick', date)
            }
          },
          {
            text: '3年',
            onClick(picker) {
              const date = new Date()
              date.setFullYear(date.getFullYear() + 3)
              date.setHours(23, 59, 59, 999)
              picker.$emit('pick', date)
            }
          },
          {
            text: '5年',
            onClick(picker) {
              const date = new Date()
              date.setFullYear(date.getFullYear() + 5)
              date.setHours(23, 59, 59, 999)
              picker.$emit('pick', date)
            }
          },
          {
            text: '10年',
            onClick(picker) {
              const date = new Date()
              date.setFullYear(date.getFullYear() + 10)
              date.setHours(23, 59, 59, 999)
              picker.$emit('pick', date)
            }
          },
          {
            text: '30年',
            onClick(picker) {
              const date = new Date()
              date.setFullYear(date.getFullYear() + 30)
              date.setHours(23, 59, 59, 999)
              picker.$emit('pick', date)
            }
          }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    resetTemp() {
      // 计算一年后的日期，设置时间为23:59:59
      const oneYearLater = new Date()
      oneYearLater.setFullYear(oneYearLater.getFullYear() + 1)
      oneYearLater.setHours(23, 59, 59, 999)
      const defaultDate = oneYearLater.toISOString().slice(0, 19).replace('T', ' ')

      this.temp = {
        name: '',
        dingding_alert_link: '',
        is_seo_title_need_check: false,
        isEnable: true,
        vip_grade: 0,
        is_npc: false,
        end_date: defaultDate,
        auto_post_translate: false,
        enable_incremental_translation: true,
        incremental_translation_threshold: 70
      }
    },
    handleSendDingdingMsg(row) {
      this.dingdingForm.project_id = Array.isArray(row) ? row.map(item => item.id) : row.id
      this.dingdingForm.content = ''
      this.dingdingDialogVisible = true
    },
    confirmSendDingding() {
      if (!this.dingdingForm.content) {
        this.$message({
          message: '请输入消息内容',
          type: 'warning'
        })
        return
      }
      SendDingdingMsg(this.dingdingForm).then(response => {
        this.notify('发送成功')
        this.dingdingDialogVisible = false
      }).catch(err => {
        console.log(err)
        this.$message({
          message: '发送失败',
          type: 'error'
        })
      })
    },
    getList() {
      this.listLoading = false
      Get(null, qs.stringify({
        kw: this.kwInput,
        pagesize: this.pagesize,
        page: this.page,
        order_by: this.order_by,
        order_desc: this.order_desc,
        vip_grade: this.vipGradeFilter,
        is_enable: this.isEnableFilter
      }))
        .then(response => {
          this.data = response.data.data.map(v => {
            this.$set(v, 'edit', false)
            v.raw_name = v.name
            v.raw_dingding_alert_link = v.dingding_alert_link
            v.raw_is_npc = v.is_npc
            v.raw_vip_grade = v.vip_grade
            v.raw_is_seo_title_need_check = v.is_seo_title_need_check
            v.raw_isEnable = v.isEnable
            v.raw_end_date = v.end_date
            v.raw_auto_post_translate = v.auto_post_translate
            v.raw_enable_incremental_translation = v.enable_incremental_translation
            v.raw_incremental_translation_threshold = v.incremental_translation_threshold
            return v
          })
          this.total = response.data.total
          this.listLoading = true
        })
        .catch(err => {
          console.log(err)
          this.listLoading = true
        })
    },
    handleAction(action, row) {
      this.action = action
      this.dialogVisible = true
      switch (action) {
        case 'create':
          this.title = row
          this.resetTemp()
          break
        case 'delete':
          this.title = `确认要删除${row.name}?`
          this.temp = row
          break
        case 'edit':
          this.title = `修改${row.name}`
          this.temp = Object.assign({}, row)
          break
        case 'staffs':
          this.$router.push({ path: 'projectuser', query: { project_id: row.id }})
          break
      }
    },
    confirm() {
      const _data = this.temp
      switch (this.action) {
        case 'create':
          Post(this.temp).then(response => {
            this.dialogVisible = false
            this.getList()
            this.notify('添加成功')
          }).catch(err => {
            console.log(err)
            this.dialogVisible = false
          })
          break
        case 'delete':
          Delete(_data.id).then((response) => {
            this.dialogVisible = false
            this.getList()
            this.notify('删除成功')
          }).catch(err => {
            console.log(err)
            this.dialogVisible = false
          })
          break
        case 'edit':
          Put(_data.id, _data).then((response) => {
            this.dialogVisible = false
            this.getList()
            this.notify('更新成功')
          }).catch(err => {
            console.log(err)
            this.dialogVisible = false
          })
          break
      }
    },
    notify(message, duration) {
      this.$notify({
        title: '成功',
        message: message,
        type: 'success',
        duration: duration || 2000
      })
    },
    // pageSize 改变后触发 table 更新
    handleSizeChange(val) {
      this.pagesize = val
      this.getList()
    },
    // page 改变后触发 table 更新
    handlePageChange(val) {
      this.page = val
      this.getList()
    },
    // 点击搜索
    handleSearch() {
      this.page = 1
      this.getList()
    },
    showText(text) {
      this.$alert(text, '内容')
    },
    // 更新名称
    handleUpdateName(row) {
      row.edit = false
      Put(row.id, {
        name: row.name,
        dingding_alert_link: row.dingding_alert_link,
        is_seo_title_need_check: row.is_seo_title_need_check,
        is_npc: row.is_npc,
        vip_grade: row.vip_grade,
        isEnable: row.isEnable,
        end_date: row.end_date,
        auto_post_translate: row.auto_post_translate,
        enable_incremental_translation: row.enable_incremental_translation,
        incremental_translation_threshold: row.incremental_translation_threshold
      })
        .then(response => {
          this.getList()
        })
        .catch(err => {
          console.log(err)
        })
    },
    // 取消
    handleCancelName(row) {
      row.name = row.raw_name
      row.dingding_alert_link = row.raw_dingding_alert_link
      row.is_npc = row.raw_is_npc
      row.vip_grade = row.raw_vip_grade
      row.isEnable = row.raw_isEnable
      row.end_date = row.raw_end_date
      row.auto_post_translate = row.raw_auto_post_translate
      row.enable_incremental_translation = row.raw_enable_incremental_translation
      row.incremental_translation_threshold = row.raw_incremental_translation_threshold
      row.edit = false
    },
    // 修改 项目属性
    handleEditProjectAttr(row) {
      console.log(111, row)
      if (row.attr) {
        this.projectAttrDialogVisible = true
        this.prjectAttrForm = row.attr
        this.currentProjectId = row.id
      }
      if (row.length) {
        this.projectAttrDialogVisible = true
        this.prjectAttrForm = []
        this.currentProjectId = row.map(v => v.id)
      }
    },
    // project form dialog 隐藏
    cancelProjectAttrDialog(v) {
      this.projectAttrDialogVisible = false
    },
    // 项目中当前已勾选 rows 列表
    handleSelectionChange(val) {
      this.projectSelected = val
    },
    filterMethod(query, item) {
      return item.domain.indexOf(query) > -1
    },
    handleSort(v) {
      this.order_by = v.prop
      this.order_desc = orderMapper[v.order]
      this.getList()
    },
    getDingdingLinkDisplay(link) {
      if (link && link.length > 6) {
        return link.slice(-6)
      }
      return link
    },
    getExpiryStatusClass(end_date) {
      if (!end_date) return ''
      const now = new Date()
      const expiryDate = new Date(end_date)
      const diffTime = expiryDate - now
      const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))

      if (diffDays < 0) return 'status-expired' // 已过期
      if (diffDays <= 30) return 'status-expiring-soon' // 一个月内到期
      return 'status-normal' // 正常
    },
    getExpiryStatusText(end_date) {
      if (!end_date) return '未设置'
      const now = new Date()
      const expiryDate = new Date(end_date)
      const diffTime = expiryDate - now
      const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))

      if (diffDays < 0) return `已过期${Math.abs(diffDays)}天`
      if (diffDays <= 30) return `${diffDays}天后到期`
      return '正常服务期内'
    }
  }
}
</script>

<style scoped>
  .input-with-select {
    width: calc(100% - 200px);
  }

  .top {
    padding-left: 20px;
    margin-bottom: 30px;
    margin-top: 28px;
  }

  .filter-container {
    padding-left: 20px;
    margin-bottom: 20px;
  }

  .add-btn {
    float: right;
    margin-right: 20px;
    width: 130px
  }

  .mt-pagination {
    float: right;
    margin-top: 5px;
  }

  .name-input {
    width: 500px;
  }

  /* 时间状态样式 */
  .status-expired {
    color: #f56c6c;
    font-weight: bold;
    background-color: #fef0f0;
    padding: 2px 4px;
    border-radius: 3px;
  }

  .status-expiring-soon {
    color: #e6a23c;
    font-weight: bold;
    background-color: #fdf6ec;
    padding: 2px 4px;
    border-radius: 3px;
  }

  .status-normal {
    color: #67c23a;
    font-weight: normal;
  }
</style>
